// 清理可能存在的旧实例
if (typeof taskList !== 'undefined' && taskList.table) {
    try {
        taskList.table.destroy();
        $('#taskTable').empty();
        console.log('✅ 旧DataTable实例清理成功');
    } catch (e) {
        console.error('❌ 清理旧DataTable实例失败:', e);
    }
}

// 任务管理
var taskList = {
    table: null,
    createModal: null,
    detailModal: null,
    selectedQuestions: [], // 已选择的问句ID列表

    // 初始化
    init: function() {
        console.log('初始化任务管理页面...');
        this.initModals();
        this.initTable();
        this.loadStats();
        // ⭐ 产品和类别列表在打开创建对话框时才加载（showCreateModal中）
        // this.loadProductList();  // 移除，避免对话框未打开时加载
        // this.loadCategoryList(); // 移除，避免对话框未打开时加载
        this.bindEvents();
    },

    // 初始化模态框
    initModals: function() {
        this.createModal = new bootstrap.Modal(document.getElementById('createTaskModal'));
        this.detailModal = new bootstrap.Modal(document.getElementById('taskDetailModal'));
    },

    // 初始化表格
    initTable: function() {
        const self = this;
        
        console.log('🔧 开始初始化DataTable');
        console.log('🔧 检查表格元素:', $('#taskTable').length > 0 ? '存在' : '不存在');
        
        this.table = $('#taskTable').DataTable({
            processing: true,
            serverSide: false,
            ajax: function(data, callback) {
                console.log('🔧 DataTable ajax回调被调用');
                console.log('🔧 data参数:', data);
                const status = $('#filterStatus').val();
                taskApi.getList(1, 100, status).then(res => {
                    console.log('✅ 任务列表API响应:', res);
                    console.log('✅ res.data:', res.data);
                    
                    // 判断响应结构：如果res有status属性，说明是完整的axios响应
                    const isAxiosResponse = res.hasOwnProperty('status');
                    console.log('✅ 是否是axios完整响应:', isAxiosResponse);
                    
                    // 获取业务数据
                    const businessData = isAxiosResponse ? res.data : res;
                    console.log('✅ 业务数据:', businessData);
                    console.log('✅ businessData.data:', businessData.data);
                    console.log('✅ businessData.data.list:', businessData.data ? businessData.data.list : 'undefined');
                    
                    // 处理响应数据
                    const taskList = (businessData.data && businessData.data.list) ? businessData.data.list : [];
                    console.log('✅ 解析后的任务列表:', taskList);
                    console.log('✅ 任务数量:', taskList.length);
                    
                    // 如果有数据，打印第一条
                    if (taskList.length > 0) {
                        console.log('✅ 第一条任务数据:', taskList[0]);
                        console.log('✅ 第一条任务的taskId:', taskList[0].taskId);
                        console.log('✅ 第一条任务的taskName:', taskList[0].taskName);
                    }
                    
                    console.log('✅ 准备调用DataTable的callback');
                    callback({
                        data: taskList
                    });
                    console.log('✅ DataTable callback已调用');
                }).catch(err => {
                    console.error('❌ 加载任务列表失败:', err);
                    callback({ data: [] });
                });
            },
            columns: [
                { data: 'taskId' },
                { 
                    data: 'taskName',
                    render: function(data, type, row) {
                        return `<strong>${data}</strong>`;
                    }
                },
                { data: 'totalQuestionCount' },
                { data: 'totalPlatformCount' },
                { 
                    data: 'taskStatus',
                    render: function(data) {
                        const statusMap = {
                            'pending': '<span class="badge bg-warning">待执行</span>',
                            'running': '<span class="badge bg-info">执行中</span>',
                            'completed': '<span class="badge bg-success">已完成</span>',
                            'cancelled': '<span class="badge bg-secondary">已取消</span>',
                            'failed': '<span class="badge bg-danger">失败</span>'
                        };
                        return statusMap[data] || data;
                    }
                },
                { 
                    data: null,
                    render: function(data, type, row) {
                        const percentage = row.progressPercentage || 0;
                        return `
                            <div class="progress" style="height: 20px;">
                                <div class="progress-bar" role="progressbar" 
                                     style="width: ${percentage}%"
                                     aria-valuenow="${percentage}" aria-valuemin="0" aria-valuemax="100">
                                    ${row.progressCompleted}/${row.totalQuestionCount} (${percentage}%)
                                </div>
                            </div>
                        `;
                    }
                },
                { 
                    data: null,
                    render: function(data, type, row) {
                        if (row.totalCollectCount === 0) return '0%';
                        const rate = ((row.successCount / row.totalCollectCount) * 100).toFixed(2);
                        return `${row.successCount}/${row.totalCollectCount} (${rate}%)`;
                    }
                },
                { 
                    data: 'createTime',
                    render: function(data) {
                        return data ? new Date(data).toLocaleString('zh-CN') : '-';
                    }
                },
                { 
                    data: null,
                    render: function(data, type, row) {
                        let buttons = `
                            <button class="btn btn-sm btn-info view-detail" data-id="${row.taskId}">
                                <i class="fas fa-eye"></i> 详情
                            </button>
                        `;
                        
                        if (row.taskStatus === 'pending' || row.taskStatus === 'running') {
                            buttons += `
                                <button class="btn btn-sm btn-warning cancel-task" data-id="${row.taskId}">
                                    <i class="fas fa-stop"></i> 取消
                                </button>
                            `;
                        }
                        
                        // 已完成的任务可以生成分析
                        if (row.taskStatus === 'completed') {
                            buttons += `
                                <button class="btn btn-sm btn-success generate-analysis" data-id="${row.taskId}">
                                    <i class="fas fa-chart-line"></i> 生成分析
                                </button>
                            `;
                        }
                        
                        if (row.taskStatus === 'cancelled' || row.taskStatus === 'completed' || row.taskStatus === 'failed') {
                            buttons += `
                                <button class="btn btn-sm btn-danger delete-task" data-id="${row.taskId}">
                                    <i class="fas fa-trash"></i> 删除
                                </button>
                            `;
                        }
                        
                        return buttons;
                    }
                }
            ],
            order: [[0, 'desc']],
            language: {
                url: null,
                processing: "加载中...",
                search: "搜索:",
                lengthMenu: "显示 _MENU_ 条",
                info: "显示 _START_ 到 _END_ 条，共 _TOTAL_ 条",
                infoEmpty: "暂无数据",
                infoFiltered: "(从 _MAX_ 条中过滤)",
                zeroRecords: "暂无匹配数据",
                emptyTable: "暂无数据",
                paginate: {
                    first: "首页",
                    previous: "上一页",
                    next: "下一页",
                    last: "末页"
                }
            }
        });
        
        console.log('🔧 DataTable初始化完成');
        console.log('🔧 DataTable实例:', this.table);
    },

    // 加载统计数据
    loadStats: function() {
        taskApi.getList(1, 1000, '').then(res => {
            // 兼容处理：判断是否是完整的axios响应
            const businessData = res.hasOwnProperty('status') ? res.data : res;
            const tasks = (businessData.data && businessData.data.list) ? businessData.data.list : [];
            
            const stats = {
                total: tasks.length,
                pending: tasks.filter(t => t.taskStatus === 'pending').length,
                running: tasks.filter(t => t.taskStatus === 'running').length,
                completed: tasks.filter(t => t.taskStatus === 'completed').length
            };
            
            // 计算总成功率
            let totalSuccess = 0, totalCollect = 0;
            tasks.forEach(t => {
                totalSuccess += t.successCount || 0;
                totalCollect += t.totalCollectCount || 0;
            });
            const successRate = totalCollect > 0 ? ((totalSuccess / totalCollect) * 100).toFixed(2) : 0;
            
            $('#totalTasks').text(stats.total);
            $('#pendingTasks').text(stats.pending);
            $('#runningTasks').text(stats.running);
            $('#completedTasks').text(stats.completed);
            $('#successRate').text(successRate + '%');
        });
    },

    // 加载产品列表（只加载我方产品）
    loadProductList: function() {
        productApi.getList({ 
            page: 1, 
            size: 1000, 
            isOurProduct: 1  // ⭐ 只获取我方产品，不包括竞品
        }).then(res => {
            // 兼容处理：判断是否是完整的axios响应
            const businessData = res.hasOwnProperty('status') ? res.data : res;
            const products = (businessData.data && businessData.data.list) ? businessData.data.list : [];
            
            console.log('✅ 加载我方产品列表，数量:', products.length);
            
            const select = $('#filterByProduct');
            select.empty().append('<option value="">按产品筛选...</option>');
            
            // 按产品名称排序
            products.sort((a, b) => a.productName.localeCompare(b.productName, 'zh-CN'));
            
            products.forEach(p => {
                const brandInfo = p.brand ? ` (${p.brand})` : '';
                select.append(`<option value="${p.productId}">${p.productName}${brandInfo}</option>`);
            });
        }).catch(err => {
            console.error('❌ 加载产品列表失败:', err);
        });
    },

    // 加载类别列表
    loadCategoryList: function() {
        categoryApi.getList(1, 1000).then(res => {
            // 兼容处理：判断是否是完整的axios响应
            const businessData = res.hasOwnProperty('status') ? res.data : res;
            
            // 处理两种可能的返回格式
            let categories = [];
            if (businessData.data && businessData.data.list) {
                // 分页格式: {list: [...], total: x}
                categories = businessData.data.list;
            } else if (Array.isArray(businessData.data)) {
                // 数组格式: [...]
                categories = businessData.data;
            }
            
            console.log('✅ 加载产品类别列表，数量:', categories.length);
            
            const select = $('#filterByCategory');
            select.empty().append('<option value="">按类别筛选...</option>');
            
            // 只显示启用的类别，按名称排序
            categories
                .filter(c => c.status === 1 || c.status === '1')
                .sort((a, b) => a.categoryName.localeCompare(b.categoryName, 'zh-CN'))
                .forEach(c => {
                    select.append(`<option value="${c.categoryName}">${c.categoryName}</option>`);
                });
        }).catch(err => {
            console.error('❌ 加载类别列表失败:', err);
        });
    },

    // 绑定事件
    bindEvents: function() {
        const self = this;

        // 创建任务按钮
        $('#createTaskBtn').click(function() {
            self.showCreateModal();
        });

        // 搜索按钮
        $('#searchBtn').click(function() {
            self.table.ajax.reload();
            self.loadStats();
        });

        // 重置按钮
        $('#resetBtn').click(function() {
            $('#filterStatus').val('');
            $('#filterName').val('');
            self.table.ajax.reload();
            self.loadStats();
        });

        // 应用筛选按钮
        $('#applyFilterBtn').click(function() {
            self.applyQuestionFilter();
        });

        // 平台选择变化，更新预计采集次数
        $('input[type="checkbox"][id^="platform"]').change(function() {
            self.updateEstimatedCount();
        });

        // 提交任务
        $('#submitTaskBtn').click(function() {
            self.createTask();
        });

        // 查看详情
        $('#taskTable').on('click', '.view-detail', function() {
            const taskId = $(this).data('id');
            self.viewDetail(taskId);
        });

        // 取消任务
        $('#taskTable').on('click', '.cancel-task', function() {
            const taskId = $(this).data('id');
            self.cancelTask(taskId);
        });
        
        // 生成分析
        $('#taskTable').on('click', '.generate-analysis', function() {
            const taskId = $(this).data('id');
            self.generateAnalysis(taskId);
        });

        // 删除任务
        $('#taskTable').on('click', '.delete-task', function() {
            const taskId = $(this).data('id');
            self.deleteTask(taskId);
        });
    },

    // 显示创建任务模态框
    showCreateModal: function() {
        console.log('🔧 打开创建任务对话框');
        
        $('#createTaskForm')[0].reset();
        $('#questionListContainer').html('<p class="text-muted text-center">请使用上方筛选功能加载问句</p>');
        this.selectedQuestions = [];
        this.updateEstimatedCount();
        
        // ⭐ 关键：对话框打开时才加载产品和类别列表
        // 确保DOM元素已经渲染
        this.createModal.show();
        
        // 延迟100ms确保对话框完全显示后再加载数据
        setTimeout(() => {
            console.log('🔧 对话框已显示，开始加载产品和类别列表');
            console.log('🔧 检查filterByProduct元素:', $('#filterByProduct').length > 0 ? '存在' : '不存在');
            console.log('🔧 检查filterByCategory元素:', $('#filterByCategory').length > 0 ? '存在' : '不存在');
            
            this.loadProductList();
            this.loadCategoryList();
        }, 100);
    },

    // 应用问句筛选
    applyQuestionFilter: function() {
        const productId = $('#filterByProduct').val();
        const categoryName = $('#filterByCategory').val();

        console.log('🔧 应用筛选条件 - 产品ID:', productId, '类别名称:', categoryName);

        if (!productId && !categoryName) {
            Swal.fire('提示', '请选择产品或类别进行筛选', 'warning');
            return;
        }

        // 显示加载提示
        $('#questionListContainer').html('<div class="text-center py-4"><div class="spinner-border text-primary" role="status"></div><p class="mt-2 text-muted">正在加载问句...</p></div>');

        let promise;
        if (productId) {
            console.log('🔧 按产品筛选，产品ID:', productId);
            promise = questionApi.getQuestionIdsByProduct(productId);
        } else {
            console.log('🔧 按类别筛选，类别名称:', categoryName);
            promise = questionApi.getQuestionIdsByCategory(categoryName);
        }

        promise.then(res => {
            console.log('✅ 获取问句ID列表响应:', res);
            
            // 兼容处理
            const businessData = res.hasOwnProperty('status') ? res.data : res;
            const questionIds = businessData.data || businessData || [];
            
            console.log('✅ 问句ID列表:', questionIds);
            console.log('✅ 问句数量:', Array.isArray(questionIds) ? questionIds.length : 0);

            if (!Array.isArray(questionIds) || questionIds.length === 0) {
                $('#questionListContainer').html('<p class="text-muted text-center py-4">该筛选条件下暂无问句</p>');
                return;
            }

            // 批量获取问句详情
            console.log('🔧 批量获取问句详情，ID列表:', questionIds);
            return questionApi.batchGet(questionIds);
        }).then(res => {
            if (res && res.data) {
                console.log('✅ 获取问句详情响应:', res);
                
                // 兼容处理
                const businessData = res.hasOwnProperty('status') ? res.data : res;
                const questions = businessData.data || businessData || [];
                
                console.log('✅ 问句详情列表:', questions);
                console.log('✅ 问句详情数量:', Array.isArray(questions) ? questions.length : 0);
                
                this.renderQuestionList(questions);
            }
        }).catch(err => {
            console.error('❌ 加载问句失败:', err);
            $('#questionListContainer').html('<p class="text-danger text-center py-4">加载失败，请重试</p>');
            Swal.fire('错误', err.message || '加载问句失败', 'error');
        });
    },

    // 渲染问句列表
    renderQuestionList: function(questions) {
        console.log('🔧 渲染问句列表，数量:', questions ? questions.length : 0);
        
        const container = $('#questionListContainer');
        container.empty();

        if (!Array.isArray(questions) || questions.length === 0) {
            container.html('<p class="text-muted text-center py-4">暂无问句</p>');
            return;
        }

        // 添加全选/反选按钮
        container.append(`
            <div class="d-flex justify-content-between align-items-center mb-3 pb-2 border-bottom">
                <div>
                    <button type="button" class="btn btn-sm btn-outline-primary" id="selectAllQuestions">
                        <i class="fas fa-check-double"></i> 全选
                    </button>
                    <button type="button" class="btn btn-sm btn-outline-secondary ms-2" id="unselectAllQuestions">
                        <i class="fas fa-times"></i> 反选
                    </button>
                </div>
                <span class="text-muted">已选: <strong id="selectedQuestionCount">0</strong> / ${questions.length}</span>
            </div>
        `);

        questions.forEach((q, index) => {
            const checked = this.selectedQuestions.includes(q.questionId) ? 'checked' : '';
            
            // 兼容不同的字段名
            const content = q.questionContent || q.content || q.question || '未知问句';
            const category = q.category ? `<span class="badge bg-info ms-2">${q.category}</span>` : '';
            const questionId = q.questionId || q.id;
            
            container.append(`
                <div class="form-check mb-2">
                    <input class="form-check-input question-checkbox" type="checkbox" 
                           value="${questionId}" id="q${questionId}" ${checked}>
                    <label class="form-check-label" for="q${questionId}">
                        <span class="text-muted me-1">#${questionId}</span>
                        <span>${content}</span>
                        ${category}
                    </label>
                </div>
            `);
        });
        
        console.log('✅ 问句列表渲染完成');

        // 绑定复选框事件
        const self = this;
        $('.question-checkbox').change(function() {
            self.updateSelectedQuestions();
        });
        
        // 绑定全选按钮
        $('#selectAllQuestions').click(function() {
            $('.question-checkbox').prop('checked', true);
            self.updateSelectedQuestions();
        });
        
        // 绑定反选按钮
        $('#unselectAllQuestions').click(function() {
            $('.question-checkbox').each(function() {
                $(this).prop('checked', !$(this).prop('checked'));
            });
            self.updateSelectedQuestions();
        });
        
        // 初始化选中数量
        this.updateSelectedQuestions();
    },

    // 更新已选择的问句
    updateSelectedQuestions: function() {
        this.selectedQuestions = [];
        $('.question-checkbox:checked').each((i, el) => {
            this.selectedQuestions.push(parseInt($(el).val()));
        });
        
        // 更新选中数量显示（在问句列表顶部）
        $('#selectedQuestionCount').text(this.selectedQuestions.length);
        
        this.updateEstimatedCount();
    },

    // 更新预计采集次数
    updateEstimatedCount: function() {
        const questionCount = this.selectedQuestions.length;
        const platformCount = $('input[type="checkbox"][id^="platform"]:checked').length;
        const estimatedCount = questionCount * platformCount;

        $('#selectedCount').text(`已选：${questionCount}个问句`);
        $('#estimatedCount').text(`预计采集：${estimatedCount}次`);
    },

    // 创建任务
    createTask: function() {
        const taskName = $('#taskName').val().trim();
        const platforms = [];
        $('input[type="checkbox"][id^="platform"]:checked').each((i, el) => {
            platforms.push($(el).val());
        });
        const questionIds = this.selectedQuestions;
        const remark = $('#taskRemark').val().trim();

        // 验证
        if (!taskName) {
            Swal.fire('提示', '请输入任务名称', 'warning');
            return;
        }
        if (platforms.length === 0) {
            Swal.fire('提示', '请至少选择一个AI平台', 'warning');
            return;
        }
        if (questionIds.length === 0) {
            Swal.fire('提示', '请至少选择一个问句', 'warning');
            return;
        }

        // 确认
        Swal.fire({
            title: '确认创建任务？',
            html: `
                <p>任务名称：${taskName}</p>
                <p>AI平台：${platforms.join(', ')}</p>
                <p>问句数量：${questionIds.length}个</p>
                <p>预计采集：${questionIds.length * platforms.length}次</p>
            `,
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: '确认创建',
            cancelButtonText: '取消'
        }).then((result) => {
            if (result.isConfirmed) {
                this.submitTask(taskName, platforms, questionIds, remark);
            }
        });
    },

    // 提交任务
    submitTask: function(taskName, platforms, questionIds, remark) {
        const data = {
            taskName,
            platforms,
            questionIds,
            remark
        };

        taskApi.create(data).then(res => {
            Swal.fire('成功', '任务创建成功！', 'success');
            this.createModal.hide();
            this.table.ajax.reload();
            this.loadStats();
        }).catch(err => {
            console.error('创建任务失败:', err);
            Swal.fire('错误', err.message || '创建任务失败', 'error');
        });
    },

    // 查看任务详情
    viewDetail: function(taskId) {
        taskApi.getDetail(taskId).then(res => {
            console.log('✅ 任务详情API响应:', res);
            console.log('✅ res.data:', res.data);
            
            // 兼容处理：判断是否是完整的axios响应
            const businessData = res.hasOwnProperty('status') ? res.data : res;
            console.log('✅ 业务数据:', businessData);
            
            const data = businessData.data;
            console.log('✅ data:', data);
            console.log('✅ data.task:', data ? data.task : 'undefined');
            console.log('✅ data.platforms:', data ? data.platforms : 'undefined');
            console.log('✅ data.questions:', data ? data.questions : 'undefined');
            
            const task = data.task;
            const platforms = data.platforms;
            const questions = data.questions;

            let html = `
                <div class="row mb-4">
                    <div class="col-md-6">
                        <h6>基本信息</h6>
                        <table class="table table-sm">
                            <tr><td>任务ID</td><td>${task.taskId}</td></tr>
                            <tr><td>任务名称</td><td>${task.taskName}</td></tr>
                            <tr><td>任务状态</td><td>${this.getStatusBadge(task.taskStatus)}</td></tr>
                            <tr><td>问句总数</td><td>${task.totalQuestionCount}</td></tr>
                            <tr><td>平台总数</td><td>${task.totalPlatformCount}</td></tr>
                            <tr><td>总采集次数</td><td>${task.totalCollectCount}</td></tr>
                        </table>
                    </div>
                    <div class="col-md-6">
                        <h6>执行统计</h6>
                        <table class="table table-sm">
                            <tr><td>整体进度</td><td>${task.progressCompleted}/${task.totalQuestionCount} (${task.progressPercentage}%)</td></tr>
                            <tr><td>成功采集</td><td>${task.successCount}</td></tr>
                            <tr><td>失败采集</td><td>${task.failCount}</td></tr>
                            <tr><td>创建时间</td><td>${new Date(task.createTime).toLocaleString('zh-CN')}</td></tr>
                            <tr><td>开始时间</td><td>${task.startTime ? new Date(task.startTime).toLocaleString('zh-CN') : '-'}</td></tr>
                            <tr><td>结束时间</td><td>${task.endTime ? new Date(task.endTime).toLocaleString('zh-CN') : '-'}</td></tr>
                        </table>
                    </div>
                </div>

                <h6>平台列表</h6>
                <table class="table table-sm table-striped mb-4">
                    <thead>
                        <tr>
                            <th>平台名称</th>
                            <th>状态</th>
                            <th>完成进度</th>
                            <th>成功/失败</th>
                        </tr>
                    </thead>
                    <tbody>
            `;

            platforms.forEach(p => {
                html += `
                    <tr>
                        <td>${p.platformName}</td>
                        <td>${this.getStatusBadge(p.platformStatus)}</td>
                        <td>${p.completedQuestionCount}/${p.totalQuestionCount}</td>
                        <td>${p.successCount}/${p.failCount}</td>
                    </tr>
                `;
            });

            html += `
                    </tbody>
                </table>

                <h6>问句列表</h6>
                <table class="table table-sm table-striped">
                    <thead>
                        <tr>
                            <th>问句ID</th>
                            <th>问句内容</th>
                            <th>执行状态</th>
                            <th>平台进度</th>
                        </tr>
                    </thead>
                    <tbody>
            `;

            questions.forEach(q => {
                html += `
                    <tr>
                        <td>${q.questionId}</td>
                        <td>${q.questionContent}</td>
                        <td>${this.getStatusBadge(q.executeStatus)}</td>
                        <td>${q.completedPlatformCount}/${q.totalPlatformCount}</td>
                    </tr>
                `;
            });

            html += `
                    </tbody>
                </table>
            `;

            $('#taskDetailContent').html(html);
            this.detailModal.show();
        }).catch(err => {
            console.error('加载任务详情失败:', err);
            Swal.fire('错误', '加载任务详情失败', 'error');
        });
    },

    // 取消任务
    cancelTask: function(taskId) {
        Swal.fire({
            title: '确认取消任务？',
            text: '任务将被标记为已取消状态',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: '确认取消',
            cancelButtonText: '取消操作'
        }).then((result) => {
            if (result.isConfirmed) {
                taskApi.cancel(taskId).then(res => {
                    Swal.fire('成功', '任务已取消', 'success');
                    this.table.ajax.reload();
                    this.loadStats();
                }).catch(err => {
                    Swal.fire('错误', '取消任务失败', 'error');
                });
            }
        });
    },

    // 删除任务
    deleteTask: function(taskId) {
        Swal.fire({
            title: '确认删除任务？',
            text: '删除后将无法恢复，包括所有采集结果',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: '确认删除',
            confirmButtonColor: '#d33',
            cancelButtonText: '取消'
        }).then((result) => {
            if (result.isConfirmed) {
                taskApi.delete(taskId).then(res => {
                    Swal.fire('成功', '任务已删除', 'success');
                    this.table.ajax.reload();
                    this.loadStats();
                }).catch(err => {
                    Swal.fire('错误', '删除任务失败', 'error');
                });
            }
        });
    },
    
    // 生成分析
    generateAnalysis: function(taskId) {
        Swal.fire({
            title: '生成分析报告？',
            text: '将对该采集任务进行数据分析',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: '确认生成',
            confirmButtonColor: '#28a745',
            cancelButtonText: '取消'
        }).then((result) => {
            if (result.isConfirmed) {
                // 显示加载中
                Swal.fire({
                    title: '分析中...',
                    text: '正在识别商品和计算统计数据',
                    icon: 'info',
                    allowOutsideClick: false,
                    showConfirmButton: false,
                    willOpen: () => {
                        Swal.showLoading();
                    }
                });
                
                // 调用分析API（注意：不要加/api前缀，因为axios.defaults.baseURL已包含）
                axios.post(`analysis/create?collectTaskId=${taskId}`)
                    .then(res => {
                        // 注意：axios拦截器已经返回了res（即response.data），所以这里的res就是ApiResponse对象
                        console.log('✅ 分析API响应（已被拦截器处理）:', res);
                        const analysisId = res.data;
                        console.log('✅ 分析成功！analysisId:', analysisId);
                        
                        Swal.fire({
                            title: '分析完成！',
                            text: '是否立即查看分析报告？',
                            icon: 'success',
                            showCancelButton: true,
                            confirmButtonText: '查看报告',
                            cancelButtonText: '稍后查看'
                        }).then((viewResult) => {
                            if (viewResult.isConfirmed) {
                                // 跳转到分析报告页面（使用绝对路径）
                                window.location.href = `/pages/analysis/report.html?analysisId=${analysisId}`;
                            }
                        });
                    })
                    .catch(err => {
                        console.error('❌ 生成分析失败:', err);
                        Swal.fire('错误', '生成分析失败：' + err.message, 'error');
                    });
            }
        });
    },

    // 获取状态徽章
    getStatusBadge: function(status) {
        const statusMap = {
            'pending': '<span class="badge bg-warning">待执行</span>',
            'running': '<span class="badge bg-info">执行中</span>',
            'completed': '<span class="badge bg-success">已完成</span>',
            'cancelled': '<span class="badge bg-secondary">已取消</span>',
            'failed': '<span class="badge bg-danger">失败</span>',
            'success': '<span class="badge bg-success">成功</span>'
        };
        return statusMap[status] || status;
    }
};

// 页面加载完成后初始化（延迟执行，确保Axios配置生效）
$(document).ready(function() {
    console.log('页面加载完成，初始化任务管理...');
    
    // 延迟300ms执行，确保config.js和api.js都已加载完成
    setTimeout(function() {
        // 重新初始化Axios配置
        if (typeof initAxiosConfig === 'function') {
            initAxiosConfig();
        }
        
        // 确认配置已设置
        console.log('Axios baseURL:', axios.defaults.baseURL);
        console.log('API_CONFIG:', API_CONFIG);
        
        // 初始化页面
        taskList.init();
    }, 300);
});

